<?php
/**
 * Created by PhpStorm.
 * User: sunfan
 * Date: 2017/8/16
 * Time: 14:30
 */

namespace App\Controller;


class ListController extends ApiBaseController
{

    // 商品列表
    public function index(){
        $data = $this->data;
        $user_id = S($data['token'])?S($data['token']):0;
        $term_id = $data['cate_id'];
        $code = -1;
        $page = $data['page']?$data['page']:1;
        $info = array();
        $where = array(
            'status'=>1
        );
        $motion_id = $data['promotion_id']?$data['promotion_id']:0;
        if($term_id){
            $where['categpry_id'] = $term_id;
            $cates = D("Terms")->where(array('status'=>1))->field('term_id as id,parent')->select();
            $ids_arr = $this->getSubCates($cates,$term_id);
            $ids = implode(',', $ids_arr);
            if($ids){
               $ids .= ",".$term_id;
               $where['category_id'] = array('in',$ids);
            }else{
               $where['category_id'] = $term_id;
            }
        }
        try{
            $qlist = D("Product")->where($where)
                 ->limit(($page-1)*8,8)
                 ->field("id,title,desc,price,stock,start_num,step,price_plus,bazar_price,image,attrs_key,attrs_value")
                 ->select();
            $code = 0;
            $msg = "ok";
            if($qlist){
                foreach($qlist as $k => $v){
                    if($motion_id > 0){
                        $qlist[$k]['price'] = $v['price_plus'];
                    }
                    unset($qlist[$k]['price_plus']);
                    if($v['attrs_key']){
                        $parameter = D("Parameter")
                            ->where(array('product_id'=>$v['id']))
                            ->field("id,attr_title,attr_value,stock,price,price_plus")
                            ->select();
                        foreach($parameter as $pk =>$pv){
                            if($motion_id > 0){
                                $parameter[$pk]['price'] = $pv['price_plus'];
                            }
                            unset($parameter[$pk]['price_plus']);
                        }
                        foreach($parameter as $p => $q){
                            $cart = D("Cart")
                                ->where(array('user_id' => $user_id, 'product_id' => $v['id'],'attr_id'=>$q['id']))
                                ->field('id,product_sum,attr_id')
                                ->find();
                            $parameter[$p]['cart'] = $cart?$cart:array();
                        }
                        $qlist[$k]['parameter'] = $parameter;
                    }else{
                        $qlist[$k]['parameter'] = array();
                        $cart = D("Cart")
                            ->where(array('user_id' => $user_id, 'product_id' => $v['id']))
                            ->field('id,product_sum,attr_id')
                            ->find();
                        $qlist[$k]['cart'] =  $cart?$cart:array();
                    }
                }
              $code = 1;
              $info = $qlist;
            }
        }catch (\Exception $e){
              $msg = '系统错误';
        }
        $this->ApiReturn($code,$msg,$info);
    }


    //  商品详情
    public function product(){
        $data = $this->data;
        $id = $data['id'];
        $code = -1;
        $msg = "缺少参数 id";
        $info = array();
        $user_id = S($data['token'])?S($data['token']):0;
        $motion_id = $data['promotion_id']?$data['promotion_id']:0;
        if($id){
            try{
              $item = D("Product")
                  ->where(array('id'=>$id))
                  ->field("id,title,brand_id,price,price_plus,stock,start_num,step,image,unit,details,desc,sold,bazar_price,attrs_key,attrs_value")
                  ->find();
              $info = $item;
              $slide = D("ProSlider")->where(array('product_id'))->select();
              $info['slide'] = $slide;

                if($motion_id > 0){
                    $info['price'] = $info['price_plus'];
                }
                unset($info['price_plus']);
                $parameter = D("Parameter")
                    ->where(array('product_id'=>$info['id']))
                    ->field("id,attr_title,attr_value,stock,price,price_plus")
                    ->select();
                foreach($parameter as $pk =>$pv){
                    if($motion_id > 0){
                        $parameter[$pk]['price'] = $pv['price_plus'];
                    }
                    unset($parameter[$pk]['price_plus']);
                    $cart = D("Cart")
                        ->where(array('user_id' => $user_id, 'product_id' => $item['id'],'attr_id'=>$pv['id']))
                        ->field('id,product_sum,attr_id')
                        ->find();
                    $parameter[$pk]['cart'] = $cart?$cart:array();
                }
                $info['parameter'] = $parameter;
                if(!$parameter){
                    $cart = D("Cart")
                        ->where(array('user_id' => $user_id, 'product_id' => $item['id']))
                        ->field('id,product_sum,attr_id')
                        ->find();
                    $info['cart'] =  $cart?$cart:array();
                }
                unset($info['attrs_key']);
                unset($info['attrs_value']);
                $brand = D("Brand")->where(array('id'=>$info['brand_id']))->field("title,logo")->find();
                $info['brand'] = $brand;
                unset($info['brand_id']);
                $code = 1;
                $msg = "ok";
            }catch (\Exception $e){
                $msg = "系统错误";
            }
        }
        $this->ApiReturn($code,$msg,$info);
    }

    //  获取分类接口
    public function categories(){
        $code = -1;
        $info = array();
        try{
          $list = D("Terms")
              ->field('term_id as id,name,image,parent')
              ->where(array('status'=>1))
              ->select();
            $code = 0;
            $msg = "成功";
            if($list){
              $newList =  $this->getTree($list,0);
              $info = $newList;
              $code = 1;
            }
        }catch (\Exception $e){
            $msg = "系统错误";
        }
        $this->ApiReturn($code,$msg,$info);
    }

    // 获取所有子类的id

    private function getSubCates($cate = array(),$id = 0){
        $data = array();
        foreach ($cate as $v){
            if($v['parent'] == $id){
                $data[] = $v['id'];
                $data = array_merge($data,$this->getSubCates($cate,$v['id']));
            }
        }
        return $data;
    }

    // 树状结构
    private function getTree($data=array(),$id=0,$list=array()){
        foreach ($data as $key => $i) {
            if($i['parent'] == $id){
                $i['sub'] = $this->getTree($data,$i['id'],$list[$key]['sub'])?$this->getTree($data,$i['id'],$list[$key]['sub']):array();
                $list[] = $i;
            }
        }
        return $list;
    }


    //  限时抢购
    public function promotions(){
        $where = array(
            'end_time' => array('gt',time())
        );
        $code = -1;
        try{
            $code = 0;
            $msg = "成功";
            $list = D("Promotion")
                ->where($where)
                ->field("id,start_time,end_time")
                ->select();
            if($list){
                foreach($list as $k => $v){
                    $list[$k]['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
                    $list[$k]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
                }
                $code = 1;
            }
        }catch (\Exception $e){
            $msg = "系统错误";
        }
        $this->ApiReturn($code,$msg,$list);

    }

   //  限时抢购商品
    public function goods(){
        $data = $this->data;
        $page = $data['page']?$data['page']:1;
        $prm_id = $data['promotion_id']?$data['promotion_id']:0;
        $code = -1;
        if(!$prm_id){
           $this->ApiReturn(-1,'缺少参数 promotion_id');
        }
        try{
            $code = 0;
            $msg = "成功";
            $list = D("PromotionProduct")
                ->alias("pp")
                ->join("__PRODUCT__ p on pp.product_id = p.id")
                ->where(array('promotion_id'=>$prm_id))
                ->limit(($page-1)*10,10)
                ->field("product_id,title,desc,price_plus as price,image,bazar_price,sold")
                ->select();
        }catch (\Exception $e){
            $msg = "系统错误";
        }
        $this->ApiReturn($code,$msg,$list);
    }
}